// @flow
import React, { Component } from 'react'
import { AgGridReact } from 'ag-grid-react'
import styles from './HistoryDataGrid.css'
import { TableResize } from 'ag-grid-addons'
import moment from 'moment'
import R from 'ramda'
type Props = {
  rowData: Array<Object>
}
type States = {
  columnDefs: Array<Object>,
  newRowData: Array<Object>
}
export class HistoryDataGrid extends Component {
  props: Props
  state: States
  gridOptions: Object
  api: Object
  getData: () => void
  exportExcel: () => void
  onGridReady: () => void
  TableResize: () => void
  constructor (props: Props) {
    super(props)
    this.state = {
      columnDefs: [],
      newRowData: []
    }
    this.gridOptions = {
      localeText: {
        loadingOoo: '数据加载中...',
        noRowsToShow: '暂无数据',
        filterOoo: '搜索当前页面',
        equals: '等于',
        notEqual: '不等于',
        contains: '包含',
        startsWith: '开始于',
        endsWith: '结束于',
        copy: '复制',
        paste: '粘贴',
        copyWithHeaders: '带表头复制',
        toolPanel: '工具栏',
        export: '导出',
        csvExport: '导出CSV',
        excelExport: '导出Excel'
      },
      enableSorting: true,
      enableFilter: true,
      enableRangeSelection: true,
      pinnedTopRowData: [],
      rowSelection: 'single',
      rowDeselection: true,
      enableColResize: true
    }
    this.onGridReady = this.onGridReady.bind(this)
    this.TableResize = TableResize.bind(this)
    this.getData = this.getData.bind(this)
    this.exportExcel = this.exportExcel.bind(this)
  }

  componentWillMount () {
    this.getData(this.props)
  }

  componentWillReceiveProps (nextProps: Props) {
    if (!R.equals(nextProps, this.props)) {
      this.getData(nextProps)
    }
  }
  getData (props: Object) {
    const { rowData } = props
     // Defs是动态生成表格的表头
    let Defs = [
      {
        headerName: '序号',
        field: 'id',
        width: 40,
        minWidth: 40,
        maxWidth: 40,
        cellStyle: {
          'padding-top': '8px',
          'text-align': 'center'
        }
      }, {
        headerName: '时间',
        field: 'time',
        cellStyle: {
          padding: '8px'
        }
        // cellRenderer: (params) => {
        //   return moment(params.data.time).format('YYYY-MM-DD HH:mm:ss')
        // }
      }
    ]
    rowData.map((d, i) => {
      Defs.push({
        headerName: d.name,
        field: d.field + d.compoundId.channel_id,
        cellStyle: {
          padding: '8px'
        }
      })
    })
    // Rows是重新组合传来的数据以表格形式展示
    let Rows = []
    if (rowData.length > 0) {
      let data1 = []
      for (var index = 0; index < rowData.length; index++) {
        if (rowData[index].data.length > 0) {
          data1 = rowData[index].data
          break
        }
      }
      data1.map((d, i) => {
        let obj = {}
        obj['id'] = i + 1
        const time = d[0]
        obj['time'] = moment(d[0]).format('YYYY-MM-DD HH:mm:ss')
        rowData.map((dd, ii) => {
          const field = dd.field + dd.compoundId.channel_id
           // 但是不同通道的数据会差几秒（如果相同时间的显示，会造成好多数据显示不出来）
          const data = dd.data.filter((dd) => dd[0] === time)
          if (data.length > 0) {
            if (isNaN(data[0][1])) {
              obj[field] = data[0][1]
            } else {
              obj[field] = data[0][1].toFixed(3) * 1000 / 1000
            }
          } else {
            obj[field] = ''
          }
          // 这种数据会按次数顺序展示，但是不同通道的准确性不能保证
          // const data = dd.data
          // if (data.length > 0 && data[i]) {
          //   if (isNaN(data[i][1])) {
          //     obj[field] = data[i][1]
          //   } else {
          //     obj[field] = data[i][1].toFixed(3) * 1000 / 1000
          //   }
          // } else {
          //   obj[field] = ''
          // }
        })
        Rows.push(obj)
      })
    }
    this.setState({
      columnDefs: Defs,
      newRowData: Rows
    })
  }
  exportExcel (params: Object) {
    // console.log(this);
    // console.log('exportExcel----params');
    // console.log(params);
    this.api = params.api
    this.api.exportDataAsExcel({})
  }
  onGridReady (params: Object) {
    this.api = params.api
    this.api.sizeColumnsToFit()
    this.TableResize()
  }
  render () {
    const { columnDefs, newRowData } = this.state
    return (
      <div className={styles['grid']}>
        <div className={styles['content'] + ' ag-fresh'}>
          <AgGridReact
            gridOptions={this.gridOptions}
            rowHeight='34'
            headerHeight='28'
            columnDefs={columnDefs}
            rowData={newRowData}
            onGridReady={this.onGridReady}
          />
          {
            // <button onClick={this.exportExcel}>直接导出EXCEL</button>
          }
        </div>
      </div>
    )
  }
}
export default HistoryDataGrid
